package other.edan.newpaas.agent;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEvent;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventRequest;
import com.rkhd.platform.sdk.creekflow.ruleevent.RuleEventResponse;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.edan.newpaas.utils.HCXObjectService;
import other.edan.newpaas.utils.Result;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 处理代理申请下的明细数据
 * @Author 黎炎松
 * 2025-01-02 18:06
 */
public class DealAgentApply implements RuleEvent, FutureTask {
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "处理代理申请下的产品、计划 ==> ";

    /**
     * 执行触发规则触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public RuleEventResponse execute(RuleEventRequest request) throws ScriptBusinessException {
        LOGGER.info(LOGGER_MSG + "执行触发事件");

        // 后续有其他逻辑，使用异步处理
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), request.getDataId().toString());
            LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            LOGGER.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }

        RuleEventResponse response = new RuleEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }


    /**
     * 异常任务执行
     * @param s
     * @throws ScriptBusinessException
     */
    @Override
    public void execute(String s) throws ScriptBusinessException {
        dealAgentApplyDetail(Long.valueOf(s));
    }


    public static void main(String[] args) {
        HCXObjectService.isLocal = true;
        new DealAgentApply().dealAgentApplyDetail(3692348756925064L);
    }


    /**
     * 处理 签约代理申请 下的可售产品、采购计划
     * @param dataId 代理协议ID
     * @return
     */
    public Result dealAgentApplyDetail(Long dataId) {
        LOGGER.info(LOGGER_MSG + "处理开始");

        AgentAgreement__c agentAgreement = new AgentAgreement__c();
        agentAgreement.setId(dataId);
        agentAgreement = HCXObjectService.get(agentAgreement);
        Long agentSigning = agentAgreement.getAgentSigning__c();
        if (agentSigning == null) {
            LOGGER.info(LOGGER_MSG + "签约代理申请为空，无需处理");
            return Result.error("签约代理申请为空，无需处理");
        }

        // 设置 签约代理申请 下的可售产品
        List<SellableProducts__c> upKscpList = new ArrayList<>();
        String sql = "select id from sellableProducts__c where agentSigning__c = " + agentSigning;
        List<JSONObject> kscpList = HCXObjectService.queryAllUseXoql(sql);
        LOGGER.info(LOGGER_MSG + "kscpList = " + kscpList.size());
        for (JSONObject kscp : kscpList) {
            SellableProducts__c sellableProducts = new SellableProducts__c();
            sellableProducts.setId(kscp.getLong("id"));
            sellableProducts.setAgentAgreement__c(dataId);
            upKscpList.add(sellableProducts);

            if (upKscpList.size() > 100) {
                HCXObjectService.updateBatch(upKscpList);
                upKscpList.clear();
            }
        }
        HCXObjectService.updateBatch(upKscpList);

        // 采购计划
        List<PurchasePlan__c> upCgjhList = new ArrayList<>();
        sql = "select id from purchasePlan__c where signingAgent__c = " + agentSigning;
        List<JSONObject> cgjhList = HCXObjectService.queryAllUseXoql(sql);
        LOGGER.info(LOGGER_MSG + "cgjhList = " + cgjhList.size());
        for (JSONObject cgjh : cgjhList) {
            PurchasePlan__c purchasePlan = new PurchasePlan__c();
            purchasePlan.setId(cgjh.getLong("id"));
            purchasePlan.setAgentAgreement__c(dataId);
            upCgjhList.add(purchasePlan);

            if (upCgjhList.size() > 100) {
                HCXObjectService.updateBatch(upCgjhList);
                upCgjhList.clear();
            }
        }
        HCXObjectService.updateBatch(upCgjhList);

        // 代理产品及区域汇总
        List<SurrogateHospital__c> upDlcpList = new ArrayList<>();
        sql = "select id from surrogateHospital__c where contractApplication__c = " + agentSigning;
        List<JSONObject> dlcpList = HCXObjectService.queryAllUseXoql(sql);
        LOGGER.info(LOGGER_MSG + "dlcpList = " + dlcpList.size());
        for (JSONObject dlcp : dlcpList) {
            SurrogateHospital__c surrogateHospital = new SurrogateHospital__c();
            surrogateHospital.setId(dlcp.getLong("id"));
            surrogateHospital.setAgentAgreement__c(dataId);
            upDlcpList.add(surrogateHospital);

            if (upDlcpList.size() > 100) {
                HCXObjectService.updateBatch(upDlcpList);
                upDlcpList.clear();
            }
        }
        HCXObjectService.updateBatch(upDlcpList);

        LOGGER.info(LOGGER_MSG + "处理成功");
        return Result.success();
    }



}
